package com.demo.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2022-05-14 21:44
 * @Description: AnnotationParser$注解解析
 */
public class AnnotationParser {

	//解析类的注解
	public static void parseTypeAnnotation() throws ClassNotFoundException {
		Class clazz = Class.forName("com.demo.annotation.Course");
		//获取class对象的注解，非其中的方法和成员变量的注解
		Annotation[] annotations = clazz.getAnnotations();
		for (Annotation annotation : annotations) {
			CourseInfoAnnotation courseInfoAnnotation = (CourseInfoAnnotation) annotation;
			System.out.println("课程名称："+courseInfoAnnotation.courseName()+"\n"+
					"课程便签："+courseInfoAnnotation.courseTag()+"\n"+
					"课程简介："+courseInfoAnnotation.courseProfile()+"\n"+
					"课程序号："+courseInfoAnnotation.courseIndex());
		}
	}

	//解析成员变量的标签
	public static void parseFieldAnnotation() throws ClassNotFoundException {
		Class clazz = Class.forName("com.demo.annotation.Course");
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			//判断成员变量中是否有指定注解类型的注解
			boolean hasAnnotation = field.isAnnotationPresent(PersonInfoAnnotation.class);
			if(hasAnnotation){
				PersonInfoAnnotation personInfoAnnotation =
						 field.getAnnotation(PersonInfoAnnotation.class);
				System.out.println("名字："+personInfoAnnotation.name()+"\n"+
						"年龄："+personInfoAnnotation.age()+"\n"+
						"性别："+personInfoAnnotation.gender());
				for (String language : personInfoAnnotation.language()) {
					System.out.println("课程名："+language);
				}
			}
		}
	}

	public static void parseMethodAnnotation() throws ClassNotFoundException {
		Class clazz = Class.forName("com.demo.annotation.Course");
		Method[] methods = clazz.getDeclaredMethods();
		for (Method method : methods) {
			boolean annotationMethodFlag = method.isAnnotationPresent(CourseInfoAnnotation.class);
			if(annotationMethodFlag){
				CourseInfoAnnotation courseInfoAnnotation = method.getAnnotation(CourseInfoAnnotation.class);
				System.out.println("课程名："+courseInfoAnnotation.courseName()+"\n"+
						"课程标签："+courseInfoAnnotation.courseTag()+"\n"+
						"课程简介："+courseInfoAnnotation.courseProfile()+"\n"+
						"课程序号："+courseInfoAnnotation.courseIndex());
			}
		}
	}

	public static void main(String[] args) throws ClassNotFoundException {
		//parseTypeAnnotation();
		parseFieldAnnotation();
		//parseMethodAnnotation();

		//保留中间代理类对象
		//打印加载类的详情，跟踪类加载
	}


}
